package com.tywj.buscustomerapp.view.activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.utils.overlay.SmoothMoveMarker;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.amap.api.trace.LBSTraceClient;
import com.amap.api.trace.TraceLocation;
import com.amap.api.trace.TraceStatusListener;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.tywj.buscustomerapp.Config;
import com.tywj.buscustomerapp.R;
import com.tywj.buscustomerapp.model.bean.BaseReqeust;
import com.tywj.buscustomerapp.model.bean.MonthTBean;
import com.tywj.buscustomerapp.model.bean.MyTicketBean;
import com.tywj.buscustomerapp.model.bean.StationBean;
import com.tywj.buscustomerapp.model.bean.TravelBean;
import com.tywj.buscustomerapp.presenter.BasePresenter;
import com.tywj.buscustomerapp.presenter.MapTicketPresenter;
import com.tywj.buscustomerapp.presenter.contract.MapTicketContract;
import com.tywj.buscustomerapp.utils.DrivingRouteOverlay;
import com.tywj.buscustomerapp.utils.TimeRender;
import com.tywj.buscustomerapp.utils.ToastUtils;
import com.tywj.buscustomerapp.utils.WebServicrUtils;
import com.tywj.buscustomerapp.view.myview.LoadingDialog;
import com.tywj.buscustomerapp.view.myview.TaylorImagWindow;
import com.tywj.buscustomerapp.view.myview.TaylorPopupWindowD;
import com.tywj.buscustomerapp.view.myview.ToastJoe;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MapTicketActivity extends BaseActivityMvp implements MapTicketContract.MapTicketView {
    private MapView mapView;
    private TextView title;
    private ImageView back;
    private TextView ticket;
    private TextView backTicket;
    private TextView daohang;
    private AMap aMap;
    private RouteSearch routeSearch ;
    private SmoothMoveMarker moveMarker;
    private DrivingRouteOverlay drivingRouteOverlay;
    private List<LatLng> movePath;
    private List<LatLng> moveLat = new ArrayList<>();
    private MapTicketContract.MapTicketPresenter presenter = new MapTicketPresenter(this);
    private MyTicketBean myTicketBean;
    private TravelBean.DataBean.ResultListBean ticketBean;
    private MonthTBean.DataBean monthTicket;
    private Thread thread;
    private LoadingDialog waitDialog;
    private boolean threaIsCloase = false;
    private Marker clickMarker = null;

    private ImageView start_location;
    private ImageView show_road;
    private ImageView bus_location;
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    private boolean isShowRound = false;//是否展示路况


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.AppTheme1);
        mapView.onCreate(savedInstanceState);
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_map_ticket;
    }

    @Override
    public void initView() {
        mapView  = findViewById(R.id.map);
        title = findViewById(R.id.head_title);
        back = findViewById(R.id.head_left);
        ticket = findViewById(R.id.ticket);
        daohang = findViewById(R.id.daohang);
        backTicket = findViewById(R.id.head_right);
        start_location = findViewById(R.id.start_location);
        show_road = findViewById(R.id.show_road);
        bus_location = findViewById(R.id.bus_location);
        show_road.setOnClickListener(this);
        start_location.setOnClickListener(this);
        backTicket.setOnClickListener(this);
        bus_location.setOnClickListener(this);
        daohang.setOnClickListener(this);
        if (getIntent()!=null){
            myTicketBean = (MyTicketBean) getIntent().getSerializableExtra("ticket");
            if (myTicketBean==null){
                ticketBean = (TravelBean.DataBean.ResultListBean) getIntent().getSerializableExtra("tic");
                backTicket.setVisibility(View.GONE);
            }else{
                start = myTicketBean.getMyStart();
            }
            if (ticketBean==null && myTicketBean==null){
                monthTicket = (MonthTBean.DataBean) getIntent().getSerializableExtra("month");
                backTicket.setVisibility(View.GONE);
                start = monthTicket.getGmqsz();
            }else{
                if (myTicketBean==null)
                    start = ticketBean.getGmqsz();
            }
        }
        title.setText("详情");
        back.setOnClickListener(this);
        ticket.setOnClickListener(this);
        aMap = mapView.getMap();
        aMap.getUiSettings().setZoomControlsEnabled(false);
        initMap();
        startGetLocation();
        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        BitmapDescriptor descriptor = BitmapDescriptorFactory.fromResource(R.mipmap.icon_my_lo);
        myLocationStyle.myLocationIcon(descriptor);
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);//连续定位、蓝点不会移动到地图中心点，定位点依照设备方向旋转，并且蓝点会跟随设备移动。
        myLocationStyle.radiusFillColor(getResources().getColor(R.color.transparent));
        myLocationStyle.strokeColor(getResources().getColor(R.color.transparent));
        myLocationStyle.interval(5000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);
    }

    @Override
    public void initData() {
        copyFile();
        aMap.setInfoWindowAdapter(new AMap.InfoWindowAdapter() {
            View infoWindow = null;

            @Override
            public View getInfoWindow(Marker marker) {
                if(infoWindow == null) {
                    infoWindow = LayoutInflater.from(getApplicationContext()).inflate(
                            R.layout.map_infiwindow_layout, null);
                }
                render(marker, infoWindow);
                return infoWindow;
            }

            public void render(final Marker marker, View view) {
                TextView time = view.findViewById(R.id.time);
                TextView name = view.findViewById(R.id.name);
                TextView photo = view.findViewById(R.id.photo);
                TextView daohang = view.findViewById(R.id.daohang);
                String infos[] = marker.getSnippet().split("？");
                time.setText(infos[0]);
                name.setText(marker.getTitle());
                photo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (marker.getTitle()!=null && !marker.getTitle().equals("")){
                            String path = marker.getSnippet().split("？")[1];
                            String info = marker.getSnippet().split("？")[2];
                            Log.i("taylor",path);
                            if (path!=null && !path.equals("") && !path.equals("null") && path.length()>0) {
                                TaylorImagWindow mPopwindow = new TaylorImagWindow(mContext, path,info);
                                mPopwindow.show();
                            }else{
                                ToastUtils.show("暂无站点图片");
                            }
                        }
                    }
                });
                daohang.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TaylorPopupWindowD popupWindow = new TaylorPopupWindowD(MapTicketActivity.this,marker.getPosition());
                        popupWindow.showAtDropDownCenter(v);
                    }
                });
            }

            @Override
            public View getInfoContents(Marker marker) {
                return null;
            }
        });
        aMap.setOnInfoWindowClickListener(new AMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                if (marker.getTitle()!=null && !marker.getTitle().equals("")){
                    String path = marker.getSnippet().split("？")[1];
                    String info = marker.getSnippet().split("？")[2];
                    Log.i("taylor",path);
                    if (path!=null && !path.equals("") && !path.equals("null") && path.length()>0) {
                        TaylorImagWindow mPopwindow = new TaylorImagWindow(mContext, path,info);
                        mPopwindow.show();
                    }else{
                        ToastUtils.show("暂无站点图片");
                    }
                }

            }
        });
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker.getTitle()!=null && !marker.getTitle().equals("")){
                    clickMarker = marker;
                    clickMarker.showInfoWindow();
                }
                return true;
            }
        });
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (clickMarker!=null && clickMarker.isInfoWindowShown()){
                    clickMarker.hideInfoWindow();
                    clickMarker = null;
                }
            }
        });
    }
    private void copyFile(){
        try {
            // 先获取系统默认的文档存放根目录
            File parent_path = Environment.getExternalStorageDirectory();
            File dir = new File(parent_path.getAbsoluteFile(), "com.tywj.buscustomerapp");
            if(!dir.exists()){

                dir.mkdir();
            }
            File file = new File(dir.getAbsoluteFile(), "style.data");
            if(file.exists()){
                aMap.setCustomMapStylePath(dir.getAbsolutePath()+"/style.data");
                aMap.setMapCustomEnable(true);
                return;
            }
            //读取数据文件getResources().openRawResource(R.raw.qq);
            InputStream open = this.getResources().openRawResource(R.raw.style);
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            int len;
            byte[] buf = new byte[1024];
            while((len=open.read(buf))!=-1){
                fos.write(buf,0,len);
            }
            aMap.setCustomMapStylePath(file.getAbsolutePath());
            aMap.setMapCustomEnable(true);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void startGetLocation(){
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
//        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setLocationCacheEnable(false);//关闭定位缓存
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            LatLng latLng = new LatLng(aMapLocation.getLatitude(),aMapLocation.getLongitude());
            CameraUpdate up = CameraUpdateFactory.changeLatLng(latLng);
            up.getCameraUpdateFactoryDelegate().zoom =18;
            aMap.animateCamera(up);
        }
    };


    private void initMap(){
        //添加marker
        if (moveMarker==null) {
            moveMarker = new SmoothMoveMarker(aMap);
            moveMarker.setDescriptor(BitmapDescriptorFactory.fromResource(R.mipmap.dgp_gn_icon_bus));
        }
        if (myTicketBean!=null) {
            presenter.startLoadStations(myTicketBean.getTravelNum());
        }else if (monthTicket!=null){
            presenter.startLoadStations(monthTicket.getCh());
        }else if (ticketBean!=null){
            presenter.startLoadStations(ticketBean.getCh());
        }
    }
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==20010){
                LatLng latLng = (LatLng) msg.obj;
                if (latLng==null){
                    //todo这里没有，判断是不是没发车或者已结束
                    finish();
                    return;
                }
                if (latLng.longitude==0.0 && latLng.latitude==0.0){
                    ToastJoe.getmToastJoe().ToastShowRight(MapTicketActivity.this,null,"本次行程已结束，欢迎下次乘坐");
                    finish();
                }
                if (latLng.longitude==1.0 && latLng.latitude==1.0){

                }else{
                    if (latLng!=null){
                        moveLat.add(latLng);
                    }
                    if (moveLat!=null){
                        if (moveLat.size()<2){
                            startMoveCar1(moveLat.get(0),moveLat.get(0));
                        }else{
                            startMoveCar1(moveLat.get(moveLat.size()-2),moveLat.get(moveLat.size()-1));
                        }
//                        if (moveLat.size()==1){
//
//                            startRouteSearch(moveLat.get(0),moveLat.get(0),null,false);
//                        }else if (moveLat.size()>1){
//                            float distance = AMapUtils.calculateLineDistance(moveLat.get(moveLat.size()-2),moveLat.get(moveLat.size()-1));
//                            if (distance<=3){
//                                moveLat.remove(moveLat.size() - 1);
//                            }else {
//                                startRouteSearch(moveLat.get(moveLat.size() - 2), moveLat.get(moveLat.size() - 1), null, false);
//                            }
//                        }
                    }
                }


            }
        }
    };

    @Override
    protected BasePresenter bindPresenter() {
        return presenter;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.head_left:
                finish();
                break;
            case R.id.ticket:
                if (myTicketBean!=null) {
                    Log.i("test1","1");
                    Intent intent = new Intent(MapTicketActivity.this, MyTicketActivity.class);
                    intent.putExtra("ticketID", myTicketBean.getId());
                    startActivity(intent);
                } else if (ticketBean!=null ){
                    if (ticketBean.getTicketType()==1){
                        Intent intent = new Intent(MapTicketActivity.this, MyMonthTicketActivity.class);
                        startActivity(intent);
                    }else {
                        Intent intent = new Intent(MapTicketActivity.this, MyTicketActivity.class);
                        intent.putExtra("ticketID", ticketBean.getId());
                        startActivity(intent);
                    }
                } else{
                    Intent intent = new Intent(MapTicketActivity.this, MyMonthTicketActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.head_right:
                if (myTicketBean!=null && !myTicketBean.isMonth) {
                    if (myTicketBean.getState().equals("待乘车")) {
                        showDialog("退票？", "确定退票？");
                    } else {
                        ToastJoe.getmToastJoe().ToastShow(MapTicketActivity.this, null, "当前班次不支持退票");
                    }
                }else if (monthTicket!=null){
                    backTicket.setVisibility(View.GONE);
//                    boolean b1 = Integer.valueOf(TimeRender.getFullDateStr10()[0])<Integer.valueOf(myTicketBean.getYear());
//                    boolean b2 = Integer.valueOf(TimeRender.getFullDateStr10()[1])<Integer.valueOf(myTicketBean.getMonth());
//                    boolean b3 = Integer.valueOf(TimeRender.getFullDateStr10()[0]).equals(Integer.valueOf(myTicketBean.getYear()));
//                    if ((b3 && b2) || b1){
//                        doCancleTicket(myTicketBean.getId(), "1");
//                    }else{
//                        ToastJoe.getmToastJoe().ToastShow(MapTicketActivity.this, null,  TimeRender.getFullDateStr10()[0]+"当前班次不支持退票"+myTicketBean.getYear());
//                    }

                }else if (ticketBean!=null){
                    backTicket.setVisibility(View.GONE);
                }
                break;
            case R.id.show_road:
                if (isShowRound){
                    show_road.setImageResource(R.mipmap.icon_traffic);
                }else{
                    show_road.setImageResource(R.mipmap.icon_traffic_pre);
                }
                aMap.setTrafficEnabled(!isShowRound);
                isShowRound = !isShowRound;
                break;
            case R.id.start_location:
                if (mLocationClient!=null)
                    mLocationClient.startLocation();
                break;
            case R.id.bus_location:
                if (moveLat.size()>0){
                    LatLng latLng = new LatLng(moveLat.get(moveLat.size()-1).latitude,moveLat.get(moveLat.size()-1).longitude);
                    CameraUpdate up = CameraUpdateFactory.changeLatLng(latLng);
                    up.getCameraUpdateFactoryDelegate().zoom =13;
                    aMap.animateCamera(up);
                }else{
                    ToastJoe.getmToastJoe().ToastShowRight(this,null,"暂未发车");
                }
                break;
            case R.id.daohang:
                if (startL!=null){
                    TaylorPopupWindowD popupWindow = new TaylorPopupWindowD(this,startL);
                    popupWindow.showAtDropDownCenter(v);
                }
                break;
        }
    }

    private AlertDialog build;
    private void showDialog(final String title, final String msg){
        build = new AlertDialog.Builder(MapTicketActivity.this,R.style.AlertDialogStyle).create();
        //自定义布局
        final View view = getLayoutInflater().inflate(R.layout.dialog_cancle_layout, null);
        build.setView(view, 0, 0, 0, 0);
        build.show();
        //得到当前显示设备的宽度，单位是像素
        int width = getWindowManager().getDefaultDisplay().getWidth();
        //得到这个dialog界面的参数对象
        WindowManager.LayoutParams params = build.getWindow().getAttributes();
        //设置dialog的界面宽度
        params.width = width-(width/3);
        //设置dialog高度为包裹内容
        params.height =  WindowManager.LayoutParams.WRAP_CONTENT;
        //设置dialog的重心
        params.gravity = Gravity.CENTER;
        build.getWindow().setAttributes(params);
        build.setCanceledOnTouchOutside(true);
        TextView titleTv = view.findViewById(R.id.message);
        TextView messageTv = view.findViewById(R.id.message1);
        titleTv.setText(title);
        messageTv.setText(msg);
        Button btn_sure = view.findViewById(R.id.yes);
        Button btn_cancel = view.findViewById(R.id.no);
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doCancleTicket(myTicketBean.getId(), "0");
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                build.dismiss();
            }
        });
    }


    private void doCancleTicket(String id,String type){
        //创建一个请求队列
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        //创建一个请求
        String url = Config.SBURL + "/order/cancelOrder";
        JSONObject object = new JSONObject();
        try {
            object.put("id",id);
            object.put("type",type);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.i("taylor",String.valueOf(jsonObject));
                BaseReqeust data = new Gson().fromJson(String.valueOf(jsonObject),BaseReqeust.class);
                if (data!=null && data.getReCode().equals("201")){
                    ToastJoe.getmToastJoe().ToastShowRight(MapTicketActivity.this,null,"退票成功，钱款将在两个工作日内原路退回");
                    initData();
                }else{
                    if (data.getReCode().equals("301")){
                        ToastJoe.getmToastJoe().ToastLongShow(MapTicketActivity.this, null, data.getCodeTxt());
                    }else {
                        ToastJoe.getmToastJoe().ToastLongShow(MapTicketActivity.this, null, "退票失败");
                    }
                }
                build.dismiss();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastJoe.getmToastJoe().ToastLongShow(MapTicketActivity.this,null,"退票失败");
                build.dismiss();
            }
        });
        //将创建的请求添加到队列中
        requestQueue.add(jsonObjectRequest);
    }



    private void startRouteSearch(LatLng startL, LatLng endL, List<LatLng> roadPaths, final boolean isFirst) {
        routeSearch = new RouteSearch(this);
        routeSearch.setRouteSearchListener(new RouteSearch.OnRouteSearchListener() {
            @Override
            public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

            }
            @Override
            public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {

                if (i== AMapException.CODE_AMAP_SUCCESS) {
                    if (driveRouteResult != null && driveRouteResult.getPaths() != null) {
                        final DrivePath drivePath = driveRouteResult.getPaths()
                                .get(0);
                        if(drivePath == null) {
                            return;
                        }
                        if (isFirst) {
                            if (drivingRouteOverlay == null) {
                                if (stationBeans.size()>0){
                                    drivingRouteOverlay = new DrivingRouteOverlay(
                                            mContext, aMap, drivePath,
                                            driveRouteResult.getStartPos(),
                                            driveRouteResult.getTargetPos(), null,stationBeans.get(0),stationBeans.get(stationBeans.size()-1));
                                }else {
                                    drivingRouteOverlay = new DrivingRouteOverlay(
                                            mContext, aMap, drivePath,
                                            driveRouteResult.getStartPos(),
                                            driveRouteResult.getTargetPos(), null);
                                }
                            }
                            drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                            drivingRouteOverlay.setIsColorfulline(true);//是否用颜色展示交通拥堵情况，默认true
                            drivingRouteOverlay.removeFromMap();
                            drivingRouteOverlay.addToMap();
                            drivingRouteOverlay.zoomToSpan();
                        }else {
                            startMoveCar(drivePath);
                        }
                    }
                }
            }
            @Override
            public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

            }

            @Override
            public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

            }
        });
        LatLonPoint start = new LatLonPoint(startL.latitude,startL.longitude);
        LatLonPoint end = new LatLonPoint(endL.latitude,endL.longitude);
        List<LatLonPoint> latLonPoints = new ArrayList<>();
        if (roadPaths!=null && roadPaths.size()>0) {
            for (int i = 0; i < roadPaths.size(); i++) {
                latLonPoints.add(new LatLonPoint(roadPaths.get(i).latitude, roadPaths.get(i).longitude));
            }
        }
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(start,end);
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo,RouteSearch.DRIVING_SINGLE_DEFAULT, latLonPoints, null, "");
        routeSearch.calculateDriveRouteAsyn(query);
    }

    private void startMoveCar(final DrivePath drivePath){
        if (movePath!=null){
            movePath.clear();
        }else {
            movePath = new ArrayList<>();
        }
        for (int i = 0; i < drivePath.getSteps().size(); i++) {
            List<LatLonPoint> path = drivePath.getSteps().get(i).getPolyline();
            for (int j = 0; j < path.size(); j++) {
                movePath.add(new LatLng(path.get(j).getLatitude(),path.get(j).getLongitude()));
            }
        }
        moveMarker.setPoints(movePath);
        moveMarker.setTotalDuration(10);
        moveMarker.startSmoothMove();
    }

    private void startMoveCar1(LatLng latLng1,LatLng latLng2){
        if (movePath!=null){
            movePath.clear();
        }else {
            movePath = new ArrayList<>();
        }
        movePath.add(latLng1);
        movePath.add(latLng2);
        moveMarker.setPoints(movePath);
        moveMarker.setTotalDuration(10);
        moveMarker.startSmoothMove();
    }



    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        MobclickAgent.onPageStart("车票地图详情");
        MobclickAgent.onResume(this); //统计时长
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        MobclickAgent.onPageEnd("车票地图详情");
        MobclickAgent.onPause(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        handler.removeMessages(20010);
            try {
                if (thread!=null && thread.isAlive()) {
                    threaIsCloase = true;
                    thread.interrupt();
                    thread.join();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }

    @Override
    public void showMsg(String msg) {

    }

    @Override
    public void showLoading() {
        if (waitDialog==null)
            waitDialog = new LoadingDialog(MapTicketActivity.this);
        if (!waitDialog.isShowing())
            waitDialog.show();
    }

    @Override
    public void closeLoading() {
        if (waitDialog!=null && waitDialog.isShowing())
            waitDialog.dismiss();
    }

    private List<StationBean> stationBeans;
    private LatLng startL = null;
    private String start = "";
    @Override
    public void loadedStation(List<StationBean> s) {
        stationBeans = s;
        final List<LatLng> latLonts = new ArrayList<>();
        List<LatLng> paths = new ArrayList<>();
        for (int i = 0; i < s.size(); i++) {
            latLonts.add(new LatLng(s.get(i).getLat(),s.get(i).getLng()));
            if (s.get(i).getName().equals(start)){
                startL = new LatLng(s.get(i).getLat(),s.get(i).getLng());
            }
        }
        if (s.size()>2){
            paths.addAll(latLonts);
            paths.remove(0);
            paths.remove(paths.size()-1);
        }
//        presenter.getBusLocation(myTicketBean.getTravelNum(),myTicketBean.getCityId());
        startRouteSearch(latLonts.get(0),latLonts.get(latLonts.size()-1),paths,true);
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        String num = "";
                        String city = "001";
                        if (myTicketBean!=null){
                            num = myTicketBean.getTravelNum();
                            city = myTicketBean.getCityId();
                        }else if(monthTicket!=null){
                            num = monthTicket.getCh();
                            city = monthTicket.getCs();
                        }else if (ticketBean!=null){
                            num = ticketBean.getCh();
                            city = "001";
                        }
                        String msg  = WebServicrUtils.getInstance().getBusLocation(num,city);
                        InputStream in_nocode = new ByteArrayInputStream(msg.getBytes("UTF-8"));
                        LatLng buslatLng = WebServicrUtils.getInstance().getBusLocation(in_nocode);
                        if (threaIsCloase && (buslatLng==null || buslatLng.longitude==0.0 && buslatLng.latitude==0.0)){
                            break;
                        }
                        Message message = new Message();
                        message.what = 20010;
                        message.obj = buslatLng;
                        handler.sendMessage(message);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (XmlPullParserException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        break;
                    }
                }
            }
        });
        thread.start();
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.draggable(false);//设置Marker可拖动
        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(),R.mipmap.jing)));
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerOption.setFlat(true);//设置marker平贴地图效果
        for (int i = 0; i < s.size()-1; i++) {
            LatLng latLng = new LatLng(s.get(i).getLat(),s.get(i).getLng());
            markerOption.title(s.get(i).getName());
            markerOption.snippet("预计到达："+s.get(i).getTime()+"？"+s.get(i).getImg()+"？"+s.get(i).getInfo());
            aMap.addMarker(markerOption.position(latLng));
        }
    }

    @Override
    public void getedLocation(LatLng latLng) {
        if (latLng!=null){
            moveLat.add(latLng);
        }
        if (moveLat!=null){
            if (moveLat.size()==1){
                startMoveCar1(moveLat.get(0),moveLat.get(0));
//                startRouteSearch(moveLat.get(0),moveLat.get(0),null,false);
            }else if (moveLat.size()>1){
                startMoveCar1(moveLat.get(moveLat.size()-2),moveLat.get(moveLat.size()-1));
//                startMoveCar(drivePath);
//                startRouteSearch(moveLat.get(moveLat.size()-2),moveLat.get(moveLat.size()-1),null,false);
            }
        }
    }





}
